package com.reggie.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author 早睡蛋
 * @Date 2022/6/6 20:05:18
 * @Desc:Redis工具类
 */
@Component
public class RedisUtil {


    private final StringRedisTemplate stringRedisTemplate;

    public RedisUtil(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * String存入（永久）
     * @param key
     * @param value
     */
    public void setString(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    /**
     * String存入(过期时间)
     * @param key
     * @param value
     * @param time
     */
    public void setStringExpire(String key, String value, Long time){
        stringRedisTemplate.opsForValue().set(key,value, time, TimeUnit.SECONDS);
    }

    /**
     * String取出
     * @param key
     * @return
     */
    public String getString(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * String删除
     * @param key
     */
    public void delString(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 判断是否存在key
     * @param key
     * @return
     */
    public boolean existsString(String key) {
        return stringRedisTemplate.hasKey(key);
    }


    /**
     * Hash存入(永久)
     * @param key
     * @param hk
     * @param hv
     */
    public void setHash(String key,String hk,Object hv){
        stringRedisTemplate.opsForHash().put(key, hk, hv);
    }

    /**
     * Hash取出
     * @param key
     * @param hk
     * @return
     */
    public Object getHash(String key,String hk){
        return stringRedisTemplate.opsForHash().get(key, hk);
    }

    /**
     * ZSet存入
     * @param key
     * @param value
     * @param score
     */
    public void setZSet(String key, String value, Long score){
        stringRedisTemplate.opsForZSet().add(key,value,score);
    }

    /**
     * ZSet取出
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set getZSet(String key, int start, int end){
        return stringRedisTemplate.opsForZSet().reverseRangeWithScores(key,start,end);
    }
}
